from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError, ResponseValidationError
from fastapi.middleware import Middleware
from fastapi.middleware.cors import CORSMiddleware

from app.router import app_router
from core.exceptions import HttpExcHandle, RequestValidationHandle, ResponseValidationHandle
from core.middlewares import HttpAuditLogMiddleware
from db import engine

__all__ = ["app"]

def make_middlewares():
    middleware = [
        # 配置跨域
        Middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        ),
        # Middleware(
        #     HttpAuditLogMiddleware,
        #     methods=["GET", "POST", "PUT", "DELETE"],
        #     exclude_paths=[
        #         "/api/v1/base/access_token",
        #         "/docs",
        #         "/openapi.json",
        #     ],
        # ),
    ]
    return middleware

def register_exceptions(app: FastAPI):
    # app.add_exception_handler(DoesNotExist, DoesNotExistHandle)
    app.add_exception_handler(HTTPException, HttpExcHandle)
    # app.add_exception_handler(IntegrityError, IntegrityHandle)
    app.add_exception_handler(RequestValidationError, RequestValidationHandle)
    app.add_exception_handler(ResponseValidationError, ResponseValidationHandle)

def register_routers(app: FastAPI, prefix: str = "/api"):
    app.include_router(app_router, prefix=prefix)

@asynccontextmanager
async def lifespan(app: FastAPI):
    yield
    await engine.dispose()

def create_app() -> FastAPI:
    app = FastAPI(
        middleware=make_middlewares(),
        lifespan=lifespan,
    )
    register_exceptions(app)
    register_routers(app)
    return app

app = create_app()
